/**
 * 离线业务
 * Created by WMM on 2018/06/18.
 */
import { Component } from '@angular/core';
import { Camera, CameraOptions } from '@ionic-native/camera';
import { IonicPage, NavController, ToastController, NavParams, AlertController, App } from 'ionic-angular';
import { BarcodeScanner } from '@ionic-native/barcode-scanner';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';

@IonicPage()
@Component({
  selector: 'page-offline-work',
  templateUrl: 'offline-work.html'
})
export class OfflineWork {
  myAppDatabase: SQLiteObject;

  private pageType: number;
  private pageOneTag: boolean = true;
  private pageOneContainerTag: boolean;
  private pageOnematerielScanTag: boolean;
  private pageOnematerielTag: boolean;
  private pageTwoTag: boolean = true;
  private pageThreeTag: boolean = true;
  private pageErrorTag: boolean = true;
  private pageOneSaveTag: boolean = true;
  private pageTwoScanTag: boolean = true;
  private pageTwoSaveTag: boolean = true;
  private pageTwoPhotoTag: boolean = true;
  private pageThreeSaveTag: boolean = true;
  private scanfix: boolean = false;
  private LeaveTag: boolean = true;


  private bizType: number;
  private CurrentContainer: any;
  private Currentmateriel: any;
  private loadOrUnloadImgBase64: string;
  private loadOrUnloadImgNumber: number = 0;

  private loadOrUnloadObj: any;
  private loadOrUnloadList: Array<any>;

  private ruleRecordObj: any;
  private ruleRecordList: Array<any>;

  private ruleRecordmateriel: any;

  private ruleRecordImgBase64: string;
  private ruleRecordImgNumber: number = 0;
  private imgType: string = "10";

  private length: string = "";
  private width: string = "";
  private height: string = "";
  private weight: string = "";
  private description: string = "这是备注/描述...";

  private exceptionInfo: string = "";
  private exceptionInfoObj: any;
  private exceptionInfoList: Array<any>;

  private imgData: string = "assets/imgs/photo.jpg";


  //  页面即将进入时调用
  ionViewWillEnter() {
    this.getData();
  }


  //  离开页面守卫
  ionViewCanLeave(): boolean {
    if (this.scanfix) {
      return false;
    }
    if (!this.LeaveTag) {
      const confirm = this.alertCtrl.create({
        title: '确定要离开页面吗?',
        message: '您的数据还未保存,点击确定将离开界面,并且此次扫描数据不会保存!',
        buttons: [
          {
            text: '确定',
            handler: () => {
              this.LeaveTag = true;
              this.navCtrl.pop();
            }
          },
          {
            text: '取消',
            handler: () => {

            }
          }
        ]
      });
      confirm.present();
    }
    return this.LeaveTag;
  }

  constructor(private barcodeScanner: BarcodeScanner, private sqlite: SQLite, private app: App, public navCtrl: NavController, private alertCtrl: AlertController, public params: NavParams, private toastCtrl: ToastController, private camera: Camera) {
    this.pageType = params.get("pageType");
    this.CurrentContainer = {
      name: "",
      code: "",
      qrcode: "",
      type: "",
      id: ""
    };
    this.Currentmateriel = {
      materielId: "",
      pklmaterielId: "",
      name: "",
      code: "",
      weight: "",
      length: "",
      width: "",
      height: "",
      volume: "",
      qrcode: "",
      takePhoto: ""
    };
    this.loadOrUnloadImgBase64 = "";
    this.imgType = "";
    this.bizType = 10;
    this.loadOrUnloadList = [];
    this.ruleRecordList = [];
    this.exceptionInfoList = [];

    this.loadOrUnloadObj = {
      materielName: "",
      materielCode: "",
      containerName: "",
      containerCode: "",
      weight: "",
      volume: "",
      img: "",
      date: ""
    }
    this.ruleRecordObj = {
      name: "",
      code: "",
      img: "",
      qrcode: "",
      date: "",
      length: "",
      width: "",
      height: "",
      weight: "",
      description: "",
    }
    this.ruleRecordImgBase64 = "";
    this.ruleRecordmateriel = {
      qrcode: "",
      name: "",
      code: "",
      stalength: "",
      stawidth: "",
      staheight: "",
      staweight: "",
      takePhoto: "",
      materielId: "",
      pklmaterielId: ""
    }
    this.exceptionInfoObj = {
      text: "",
      date: ""
    };
    this.exceptionInfo = "";

    if (this.pageType == 1) {
      this.pageOneTag = false;
      this.pageOnematerielScanTag = true;
      this.pageOneContainerTag = true;
      this.pageOnematerielTag = true;
      this.pageTwoTag = true;
      this.pageThreeTag = true;
    } else if (this.pageType == 2) {
      this.pageOneTag = true;
      this.pageTwoTag = false;
      this.pageThreeTag = true;
    } else if (this.pageType == 3) {
      this.pageOneTag = true;
      this.pageTwoTag = true;
      this.pageThreeTag = false;
    } else {
      this.pageErrorTag = false;
    }
  }

  getData() {
    this.sqlite.create({
      name: 'ionicdb.db',
      location: 'default'
    }).then((db: SQLiteObject) => {
      if (this.pageType == 1) {
        db.executeSql('CREATE TABLE IF NOT EXISTS materiel(rowid INTEGER PRIMARY KEY ,date TEXT,companyId VARCHAR,name TEXT,code TEXT,qrcode TEXT,length decimal(50,2), width decimal(50,2), height decimal(50,2),emptyWeight decimal(50,3),volume decimal(50,3),takePhoto INT,materielId VARCHAR,pklmaterielId VARCHAR)', [])
          .then(res => console.log('初始化表 materiel'))
          .catch(e => console.log(e.messagee));
        db.executeSql('CREATE TABLE IF NOT EXISTS container(rowid INTEGER PRIMARY KEY ,date TEXT,companyId VARCHAR,id VARCHAR,name TEXT,code TEXT, qrcode TEXT,length decimal(50,3), width decimal(50,2), height decimal(50,2),deadWeight decimal(50,3),bearWeight decimal(50,3),containerType INT)', [])
          .then(res => console.log('初始化表 container'))
          .catch(e => console.log(e.message));
        db.executeSql('CREATE TABLE IF NOT EXISTS loadOrUnload(rowid INTEGER PRIMARY KEY ,date TEXT,containerId VARCHAR,containerName VARCHAR,containerCode VARCHAR, containerQrcode TEXT, materielId VARCHAR, materielName VARCHAR, materielCode VARCHAR, materielQrcode TEXT, pklmaterielId VARCHAR, bizType INT,img VARCHAR,imgType VARCHAR)', [])
          .then(res => console.log('初始化表 loadOrUnload'))
          .catch(e => console.log(e.message));
      } else if (this.pageType == 2) {
        db.executeSql('CREATE TABLE IF NOT EXISTS materiel(rowid INTEGER PRIMARY KEY ,date TEXT,companyId VARCHAR,name TEXT,code TEXT,qrcode TEXT,length decimal(50,2), width decimal(50,2), height decimal(50,2),emptyWeight decimal(50,3),volume decimal(50,3),takePhoto INT,materielId VARCHAR,pklmaterielId VARCHAR)', [])
          .then(res => console.log('初始化表 materiel'))
          .catch(e => console.log(e.messagee));
        db.executeSql('CREATE TABLE IF NOT EXISTS ruleRecord(rowid INTEGER PRIMARY KEY ,date TEXT, materielQrcode TEXT, length decimal(50,3), width decimal(50,3), height decimal(50,3),weight decimal(50,3),description TEXT,img VARCHAR,materielId VARCHAR,materielName VARCHAR, materielCode VARCHAR,pklmaterielId VARCHAR)', [])
          .then(res => console.log('初始化表 ruleRecord'))
          .catch(e => console.log(e.messagee));
      } else if (this.pageType == 3) {
        db.executeSql('CREATE TABLE IF NOT EXISTS exceptionReport(rowid INTEGER PRIMARY KEY ,date TEXT,exception TEXT)', [])
          .then(res => console.log('初始化表 exceptionReport'))
          .catch(e => console.log(e.messagee));
      } else {
        this.showMsg("非法操作,参数错误");
      }
      this.myAppDatabase = db;
    }).catch(e =>
      this.showMsg("系统Sql组件错误,请联系管理员!,错误信息为: " + e.messagee)
    );
  }


  toScan(type: string) {
    this.barcodeScanner.scan({ showTorchButton: true, resultDisplayDuration: 0 }).then((data) => {
      if (data.text.length != 0) {
        if (type == 'container') {
          this.myAppDatabase.executeSql('SELECT * FROM container WHERE qrcode= ?', [data.text])
            .then(res => {
              if (res.rows.length > 0) {
                //console.log("container res.rows.length>0 进入循环 length="+res.rows.length);
                for (var i = 0; i < res.rows.length; i++) {
                  this.CurrentContainer = {
                    name: res.rows.item(i).name,
                    code: res.rows.item(i).code,
                    qrcode: data.text,
                    type: res.rows.item(i).containerType == 1 ? "运输容器" : "仓储容器",
                    id: res.rows.item(i).id
                  }
                }
              } else {
                this.CurrentContainer = {
                  name: "未知",
                  code: "未知",
                  qrcode: data.text,
                  type: "未知",
                  id: "未知"
                }
              }
              this.pageOneSaveTag = true;
              this.pageOneContainerTag = false;
              this.imgData = "assets/imgs/photo.jpg";
            })
            .catch(e => console.log("系统Sql组件错误,请联系管理员!,错误信息为: " + e.message));
        } else if (type == 'materiel') {
          this.myAppDatabase.executeSql('SELECT * FROM materiel WHERE qrcode= ?', [data.text])
            .then(res => {
              if (res.rows.length > 0) {
                for (var i = 0; i < res.rows.length; i++) {
                  this.Currentmateriel = {
                    materielId: res.rows.item(i).materielId,
                    pklmaterielId: res.rows.item(i).pklmaterielId,
                    name: res.rows.item(i).name,
                    code: res.rows.item(i).code,
                    weight: res.rows.item(i).emptyWeight,
                    length: res.rows.item(i).length,
                    width: res.rows.item(i).width,
                    height: res.rows.item(i).height,
                    volume: res.rows.item(i).volume,
                    qrcode: data.text,
                    takePhoto: res.rows.item(i).takePhoto
                  }
                }
              } else {
                this.Currentmateriel = {
                  materielId: "未知",
                  pklmaterielId: "未知",
                  name: "未知",
                  code: "未知",
                  weight: "0",
                  length: "0",
                  width: "0",
                  height: "0",
                  volume: "0",
                  qrcode: data.text,
                  takePhoto: "未知"
                }
              }
              this.imgType = "";
              this.loadOrUnloadImgBase64 = "";
              this.loadOrUnloadImgNumber = 0;
              this.pageOnematerielScanTag = true;
              this.pageOnematerielTag = false;
              this.pageOneSaveTag = false;
              this.LeaveTag = false;
              this.bizType = 10;
            })
            .catch(e => console.log("系统Sql组件错误,请联系管理员!,错误信息为: " + e.message));
        } else if (type == 'ruleRecord') {
          this.length = "";
          this.width = "";
          this.height = "";
          this.weight = "";
          this.description = "这是备注/描述...";
          this.myAppDatabase.executeSql('SELECT * FROM materiel WHERE qrcode= ?', [data.text])
            .then(res => {
              if (res.rows.length > 0) {
                for (var i = 0; i < res.rows.length; i++) {
                  this.ruleRecordmateriel = {
                    qrcode: data.text,
                    name: res.rows.item(i).name,
                    code: res.rows.item(i).code,
                    stalength: res.rows.item(i).length,
                    stawidth: res.rows.item(i).width,
                    staheight: res.rows.item(i).height,
                    staweight: res.rows.item(i).emptyWeight,
                    takePhoto: res.rows.item(i).takePhoto,
                    materielId: res.rows.item(i).materielId,
                    pklmaterielId: res.rows.item(i).pklmaterielId,
                  }
                  this.length = res.rows.item(i).length;
                  this.width = res.rows.item(i).width;
                  this.height = res.rows.item(i).height;
                  this.weight = res.rows.item(i).emptyWeight;
                }
              } else {
                this.ruleRecordmateriel = {
                  qrcode: data.text,
                  name: "未知",
                  code: "未知",
                  stalength: "未知",
                  stawidth: "未知",
                  staheight: "未知",
                  staweight: "未知",
                  takePhoto: "未知",
                  materielId: "未知",
                  pklmaterielId: "未知",
                }
              }
              this.ruleRecordImgBase64 = "";
              this.ruleRecordImgNumber = 0;
              this.LeaveTag = false;
              this.pageTwoScanTag = false;
              this.pageTwoSaveTag = false;
              this.pageTwoPhotoTag = false;
            })
            .catch(e => console.log("系统Sql组件错误,请联系管理员!,错误信息为: " + e.message));
        } else {
          this.showMsg("非法操作,参数无效!");
        }
      } else {
        this.fixshowMsg("请扫描正确的二维码!");
      }
    }, (err) => {
      this.showMsg("扫描出现异常" + err);
    });
  }


  saveData(type: string) {
    let now: Date = new Date;
    if (type == 'loadOrUnload') {
      if ((this.CurrentContainer.name == "未知" || this.Currentmateriel.name == "未知") && this.loadOrUnloadImgNumber < 1) {
        this.showMsg("未知属性必须拍照!");
        return;
      } else if (this.Currentmateriel.takePhoto != 1 && this.loadOrUnloadImgNumber < 1) {
        this.showMsg("该货物有强制拍照属性，请拍照！");
        return;
      }
      this.cutImageBase64(this.imgData, "100", "100", (newImgData) => {
        this.loadOrUnloadObj = {
          materielName: this.Currentmateriel.name,
          materielCode: this.Currentmateriel.code,
          containerName: this.CurrentContainer.name,
          containerCode: this.CurrentContainer.code,
          weight: this.Currentmateriel.weight,
          volume: this.Currentmateriel.weight,
          img: newImgData,
          date: this.myFormat('hh:mm', now)
        }
        this.loadOrUnloadList.push(this.loadOrUnloadObj);
      });
      this.myAppDatabase.executeSql('INSERT INTO loadOrUnload VALUES (NULL,?,?,?,?,?,?,?,?,?,?,?,?,?)',
        [this.myFormat('yyyy-MM-dd hh:mm:ss', now), this.CurrentContainer.id, this.CurrentContainer.name, this.CurrentContainer.code, this.CurrentContainer.qrcode, this.Currentmateriel.materielId, this.Currentmateriel.name, this.Currentmateriel.code, this.Currentmateriel.qrcode, this.Currentmateriel.pklmaterielId, this.bizType, this.loadOrUnloadImgBase64, this.imgType])
        .then(() => {
          console.log('insert into loadOrUnload table successfully')
          this.LeaveTag = true;
        })
        .catch(e => this.showMsg("系统Sql组件错误,请联系管理员!,错误信息为: " + e));
      //清除数据
      this.loadOrUnloadObj = {
        materielName: "",
        materielCode: "",
        containerName: "",
        containerCode: "",
        weight: "",
        volume: "",
        img: "",
        date: ""
      }
      this.imgType = "";
      this.loadOrUnloadImgBase64 = "";
      this.loadOrUnloadImgNumber = 0;
      this.imgData = "assets/imgs/photo.jpg";
      this.pageOneSaveTag = true;
    } else if (type == 'ruleRecord') {
      if (this.numberCheck() && this.detection()) {
        this.cutImageBase64(this.imgData, "100", "100", (newImgData) => {
          this.ruleRecordObj = {
            name: this.ruleRecordmateriel.name,
            code: this.ruleRecordmateriel.code,
            img: newImgData,
            qrcode: this.ruleRecordmateriel.qrcode,
            date: this.myFormat('hh:mm', now),
            length: this.length,
            width: this.width,
            height: this.height,
            weight: this.weight,
            description: this.description,
            materielId: this.ruleRecordmateriel.materielId,
            pklmaterielId: this.ruleRecordmateriel.pklmaterielId
          }
          this.ruleRecordList.push(this.ruleRecordObj);
        });
        this.myAppDatabase.executeSql('INSERT INTO ruleRecord VALUES (null,?,?,?,?,?,?,?,?,?,?,?,?)',
          [this.myFormat('yyyy-MM-dd hh:mm', now), this.ruleRecordmateriel.qrcode, this.length, this.width, this.height, this.weight, this.description, this.ruleRecordImgBase64, this.ruleRecordmateriel.materielId, this.ruleRecordmateriel.name, this.ruleRecordmateriel.code, this.ruleRecordmateriel.pklmaterielId])
          .then(() => {
            console.log('insert into ruleRecord table successfully');
            this.LeaveTag = true;
          })
          .catch(e => this.showMsg("系统Sql组件错误,请联系管理员!,错误信息为: " + e.message));
        //清除数据
        this.ruleRecordObj = {
          name: "",
          code: "",
          img: "",
          qrcode: "",
          date: "",
          length: "",
          width: "",
          height: "",
          weight: "",
          description: ""
        }
        this.ruleRecordImgBase64 = "";
        this.ruleRecordImgNumber = 0;
        this.imgData = "assets/imgs/photo.jpg";
        this.pageTwoSaveTag = true;
        this.pageTwoPhotoTag = true;
      }
    } else if (type == 'exceptionReport') {
      this.exceptionInfoObj = {
        text: this.exceptionInfo,
        date: this.myFormat('hh:mm', now)
      };
      this.exceptionInfoList.push(this.exceptionInfoObj);
      this.myAppDatabase.executeSql('INSERT INTO exceptionReport VALUES (null,?,?)',
        [this.myFormat('yyyy-MM-dd hh:mm:ss', now), this.exceptionInfo])
        .then(() => {
          console.log('insert into ruleRecord table successfully')
          this.LeaveTag = true;
        })
        .catch(e => this.showMsg("系统Sql组件错误,请联系管理员!,错误信息为: " + e));
      this.exceptionInfo = "";
      this.exceptionInfoObj = {
        text: "",
        date: ""
      };
      this.pageThreeSaveTag = true;
    } else {
      this.showMsg("非法操作,参数无效!");
    }

  }

  infoChange() {
    this.pageThreeSaveTag = false;
    this.LeaveTag = false;
  }

  /**
   * 打开摄像头拍照
   */
  takePhoto(type: string) {
    const options: CameraOptions = {
      quality: 25,                                                   //相片质量 0 -100
      destinationType: this.camera.DestinationType.DATA_URL,        //DATA_URL 是 base64   FILE_URL 是文件路径
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      saveToPhotoAlbum: true,                                       //是否保存到相册
      // sourceType: this.camera.PictureSourceType.CAMERA ,         //是打开相机拍照还是打开相册选择  PHOTOLIBRARY : 相册选择, CAMERA : 拍照,
    }
    this.camera.getPicture(options).then((imageData) => {
      this.imgData = 'data:image/jpeg;base64,' + imageData;
      if (type == 'loadOrUnload') {
        this.imgType = this.imgType + this.bizType + '!';
        this.loadOrUnloadImgBase64 = this.loadOrUnloadImgBase64 + this.imgData + '!';
        this.loadOrUnloadImgNumber = this.loadOrUnloadImgNumber + 1;
      } else if (type == 'ruleRecord') {
        this.ruleRecordImgBase64 = this.loadOrUnloadImgBase64 + this.imgData + '!';
        this.ruleRecordImgNumber = this.loadOrUnloadImgNumber + 1;
      } else {
        this.showMsg("非法操作,参数无效!");
      }
    }, (err) => {
      //this.showMsg("相机异常")
    });
  }


  numberCheck() {
    let patrn = /^[0-9]+(.[0-9]{1,3})?$/;
    if (!patrn.test(this.length)) {
      this.showMsg('长度错误! 请输入正数,且保留3位小数');
      return false;
    }
    if (!patrn.test(this.width)) {
      this.showMsg('宽度错误! 请输入正数,且保留3位小数');
      return false;
    }
    if (!patrn.test(this.height)) {
      this.showMsg('高度错误! 请输入正数,且保留3位小数');
      return false;
    }
    if (!patrn.test(this.weight)) {
      this.showMsg('重量错误! 请输入正数,且保留3位小数');
      return false;
    }
    return true;
  }


  //点击取消返回
  goBack() {
    // this.ele.nativeElement.querySelector("[ng-reflect-klass='back-button']").click();
    this.navCtrl.pop();
  }


  showMsg(msg: string) {
    var toast = this.toastCtrl.create({
      message: msg,
      duration: 3000,
      position: 'bottom'
    });
    toast.present();
  }


  fixshowMsg(msg: string) {
    this.scanfix = true;
    var toast = this.toastCtrl.create({
      message: msg,
      duration: 3000,
      position: 'bottom'
    });
    toast.present();
    setTimeout(() => this.scanfix = false, 1000);
  }

  logIn() {
    let alert = this.alertCtrl.create({
      title: '使用在线功能请确保网络通畅!',
      message: "点击确定将进入登录页面!",
      buttons: ['取消',
        {
          text: '确定',
          handler: data => {
            //点击确定,跳转到登录页面
            this.app.getRootNav().push('LoginPage', { "backButtontag": true });//用this.app.getRootNav() 从根页面跳转
          }
        }]
    });
    alert.present();
  }


  //强制拍照校验
  detection() {
    //已经校验过不需要再次进行数字校验
    if (!isNaN(this.ruleRecordmateriel.takePhoto)) {
      //是否强制拍照属性
      if (this.ruleRecordmateriel.takePhoto == 0 && this.ruleRecordImgNumber < 1) {
        this.showMsg("货物有强制拍照属性，请拍照！");
        return false;
      } else {
        //是否差异超过5%
        let tag: boolean = true;
        let showInfo: string;
        let threshold: number = 5;
        let num: number;
        num = (parseFloat(this.length) - parseFloat(this.ruleRecordmateriel.stalength)) / parseFloat(this.ruleRecordmateriel.stalength) * 100;
        if (Math.abs(Number(num.toFixed(4))) > threshold && this.ruleRecordImgNumber < 1) {
          tag = false;
          showInfo = "长度差异超过" + threshold + "%,请拍照";
          this.showMsg(showInfo);
          return tag;
        }
        num = (parseFloat(this.width) - parseFloat(this.ruleRecordmateriel.stawidth)) / parseFloat(this.ruleRecordmateriel.stawidth) * 100;
        if (Math.abs(Number(num.toFixed(4))) > threshold && this.ruleRecordImgNumber < 1) {
          tag = false;
          showInfo = "宽度差异超过" + threshold + "%,请拍照";
          this.showMsg(showInfo);
          return tag;
        }
        num = (parseFloat(this.height) - parseFloat(this.ruleRecordmateriel.staheight)) / parseFloat(this.ruleRecordmateriel.staheight) * 100;
        if (Math.abs(Number(num.toFixed(4))) > threshold && this.ruleRecordImgNumber < 1) {
          tag = false;
          showInfo = "高度差异超过" + threshold + "%,请拍照";
          this.showMsg(showInfo);
          return tag;
        }
        num = (parseFloat(this.weight) - parseFloat(this.ruleRecordmateriel.staweight)) / parseFloat(this.ruleRecordmateriel.staweight) * 100;
        if (Math.abs(Number(num.toFixed(4))) > threshold && this.ruleRecordImgNumber < 1) {
          tag = false;
          showInfo = "重量差异超过" + threshold + "%,请拍照";
          this.showMsg(showInfo);
          return tag;
        }
        return tag;
      }
    } else {
      //未知属性必须拍照
      if (this.ruleRecordImgNumber < 1) {
        this.showMsg("未知属性必须拍照!");
        return false;
      } else {
        return true;
      }

    }

  }


  myFormat(fmt: string, data: Date) {
    var o = {
      "M+": data.getMonth() + 1,                 //月份
      "d+": data.getDate(),                    //日
      "h+": data.getHours(),                   //小时
      "m+": data.getMinutes(),                 //分
      "s+": data.getSeconds(),                 //秒
      "q+": Math.floor((data.getMonth() + 3) / 3), //季度
      "S": data.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
      fmt = fmt.replace(RegExp.$1, (data.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
      if (new RegExp("(" + k + ")").test(fmt))
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
  }

  cutImageBase64(base64: string, width: string, height: string, callback) {
    let newbase64: string;
    if (base64 == "assets/imgs/photo.jpg" || base64 == "") {
      newbase64 = "assets/imgs/photo.jpg";
      callback ? callback(newbase64) : null; //调用回调函数
    } else {
      let _img = new Image();
      _img.src = base64;
      _img.onload = function () {
        let _canvas = document.createElement("canvas");
        _canvas.setAttribute("width", width);
        _canvas.setAttribute("height", height);
        _canvas.getContext("2d").drawImage(_img, 0, 0, Number(width), Number(height));
        newbase64 = _canvas.toDataURL("image/jpeg");
        callback ? callback(newbase64) : null; //调用回调函数
      }
    }
  }

}
